//
//  SourceViewController.m
//  FruitsWholesaler
//
//  Created by sgone-2 on 16/4/20.
//  Copyright © 2016年 sgone. All rights reserved.
//

#import "SourceViewController.h"
#import "SoruceCell.h"
#import "MJRefresh.h"
#import "AFNetworking.h"
#import "MBProgressHUD.h"
#import "Toast+UIView.h"
#import "LoginViewController.h"
#import "OMOrderEmptyTableViewCell.h"
#import "Common.h"
#import "DataSingleton.h"
@interface SourceViewController ()<UITableViewDelegate,UITableViewDataSource>
{

    int currentPage;
    int sizeCount;
    CGFloat emptyCellHeight;


}

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong)NSMutableArray *dataArray;
@property (nonatomic,strong) SoruceCell *cell;
@property (nonatomic, strong) AFHTTPSessionManager *manager;
@property (nonatomic, strong)OMOrderEmptyTableViewCell *emptyCell;
@property (nonatomic, strong) DataSingleton *dataHandler;
@property(nonatomic,strong) NSString *download_url;


@end

@implementation SourceViewController


- (NSMutableArray *)dataArray {
    
    if (_dataArray == nil) {
        
        _dataArray = [[NSMutableArray alloc] initWithCapacity:0];
    }
    return _dataArray;
}

//afnetworking网络请求数据
- (AFHTTPSessionManager *)manager
{
    if (_manager == nil) {
        _manager  = [AFHTTPSessionManager manager];
    }
    return _manager;
    
    
}


-(void)dealloc
{

    [[NSNotificationCenter defaultCenter] removeObserver:self];


}
- (void)viewDidLoad {
    [super viewDidLoad];
//    self.topView.hidden = YES;
    
    self.dataHandler = [DataSingleton sharedDataSingleton];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.tableFooterView = [[UIView alloc] init];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(inquiryClick:) name:@"inquiryClick" object:nil];
    
    
     [self creatData];
    dispatch_async(dispatch_get_main_queue(), ^{
        
        [self banbenAPI];
        
        
        
    });
    
    
   
    
  

    
    
}



#pragma mrak 获取版本号
-(void)banbenAPI
{
    
    NSString *str = [NSString stringWithFormat:@"%@get_version",SERVER_ADDRESS];
    NSDictionary *parmas = @{@"device_type" : @"1"};
    [self.manager POST:str parameters:parmas success:^(NSURLSessionDataTask *task, id responseObject) {
        
        
        
        if ([responseObject[@"error_flag"] intValue] == 0)
        {

        
            NSString *lasteVersion2 = [[responseObject objectForKey:@"data"]objectForKey:@"version_name"];
            
            
            //获取此应用的版本号
            NSDictionary *infoDic = [[NSBundle mainBundle]infoDictionary];
            NSString *currentVersion = [infoDic objectForKey:@"CFBundleShortVersionString"];//1.0.0
            
            
            
            //产生下载链接地址
            self.download_url = [NSString stringWithFormat:@"%@",[[responseObject objectForKey:@"data"] objectForKey:@"download_url"]];
            
            
            
            
//            NSLog(@"wwwwwwww  %@   %@",currentVersion,lasteVersion2);
        
            
            //两个点的，最后那个是无效的
            
            //  NSString *trackName  = lasteVersion2;
            if (![currentVersion isEqualToString:lasteVersion2] ) {
                NSString *titleStr = [NSString stringWithFormat:@"发现新版本: %@,是否升级?",lasteVersion2];
                
                
                UIAlertView *alter = [[UIAlertView alloc]initWithTitle:@"提示" message:titleStr delegate:self cancelButtonTitle:@"稍后再说" otherButtonTitles:@"立即升级", nil];
                alter.tag = 200;
                [alter show];}
            
            
            
            
        }
        else
        {
     
        
                        NSLog(@"错误提示  %@",responseObject[@"result_msg"]);
            
        }
     
        
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        
        
        
    }];
    
    
    
}



#pragma mark -alterView代理的实现
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    
    //    NSLog(@"下载链接地址 %@",self.download_url);
    if (alertView.tag == 200 ) {
        if (buttonIndex == 1) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:self.download_url]];
            
        }
    }
    
    
}


- (void)getGoodsListByServicePage:(int)page size:(int)size {
    
    
    NSString *urlStr  = [NSString stringWithFormat:@"%@get_shop_product_list",SERVER_ADDRESS3];
    NSDictionary *parmsa = @{@"cur_page" : [NSString stringWithFormat:@"%d",page] , @"cur_size" : [NSString
    stringWithFormat:@"%d",size]};
    
    [self.manager POST:urlStr parameters:parmsa success:^(NSURLSessionDataTask *task, id responseObject) {
        

        if ([responseObject[@"error_flag"] intValue] == 0) {
            
            NSArray *array = responseObject[@"data"][@"list"];
            
            [self.dataArray removeAllObjects];
            [self.dataArray addObjectsFromArray:array];
            [self.tableView reloadData];
            [self.tableView headerEndRefreshing];
     
        }
        
        else
        {
        
            [self.tableView headerEndRefreshing];
            NSString *str = [NSString stringWithFormat:@"%@",responseObject[@"result_msg"]];
            UIAlertView *alter = [[UIAlertView alloc]initWithTitle:@"提示" message:str delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [alter show];
            
            
            
            if ([responseObject[@"result_code"] isEqualToString:@"ERR-WHO-0005"]) {
                
                //将所有存储的数据进行清除，并且跳转到登录界面
                [self.dataHandler removeLocalData:@"wTel"];
                LoginViewController *login = [[LoginViewController alloc]initWithNibName:nil bundle:nil];
                [self presentViewController:login animated:YES completion:nil];
            }
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [MBProgressHUD hideHUDForView:self.tableView animated:YES];
        [self.view makeToast:@"获取网络失败"];
        [self.tableView headerEndRefreshing];
    }];
}




- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    
    if (self.dataArray.count == 0) {
        
        return 1;
    }
    return self.dataArray.count;
}





- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{
    
    
    if (self.dataArray.count == 0) {
        
        self.emptyCell = [OMOrderEmptyTableViewCell cellWithTableView:self.tableView];
        self.emptyCell.selectionStyle = UITableViewCellSelectionStyleNone;
        emptyCellHeight = [self.emptyCell setEmptyOrderCell];
        
        return self.emptyCell;
    }
    self.cell = [SoruceCell cellWithTableView:tableView];
    self.cell.selectionStyle = UITableViewCellSelectionStyleNone;
    

    
    self.cell.messageDic = self.dataArray[indexPath.row];

    
    return self.cell;

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (self.dataArray.count == 0) {
        
        return emptyCellHeight;
    }
    return 120.0 / FDLaOt;
}


- (void)inquiryClick:(id)sender {
    
    NSNotification *user = (NSNotification *)sender;
    NSDictionary *dic = (NSDictionary *)user.userInfo;
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"topInquiryClick" object:nil userInfo:dic];
}


//- (void)dealloc {
//    
//    [[NSNotificationCenter defaultCenter] removeObserver:self];
//}



-(void)creatData
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    
    //#warning 自动刷新(一进入程序就下拉刷新)
    [self.tableView headerBeginRefreshing];
    
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [self.tableView addFooterWithTarget:self action:@selector(footerRereshing13)];
    
    // 设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
    self.tableView.headerPullToRefreshText = @"下拉可以刷新了";
    self.tableView.headerReleaseToRefreshText = @"松开马上刷新了";
    self.tableView.headerRefreshingText = @"正在帮你刷新中";
    
    
    
    self.tableView.footerPullToRefreshText = @"上拉可以加载更多";
    self.tableView.footerReleaseToRefreshText = @"松开马上刷新了";
    self.tableView.footerRefreshingText = @"正在帮你加载中";


}


- (void)headerRereshing {
    
    currentPage  = 1;
    sizeCount = 20;
    [self getDate];
}


-(void)footerRereshing13
{
    
    currentPage ++;
    sizeCount = 20;
    [self getDate2];
    
}



-(void)getDate2
{

    
    
    NSString *urlStr = [NSString stringWithFormat:@"%@get_shop_product_list",SERVER_ADDRESS3];
    NSDictionary *parmas = @{@"cur_page" : [NSString stringWithFormat:@"%d",currentPage] , @"cur_size" : [NSString stringWithFormat:@"%d",sizeCount]};
    [self.manager POST:urlStr parameters:parmas success:^(NSURLSessionDataTask *task, id responseObject) {
        
        if ([responseObject[@"error_flag"] intValue] == 0) {
            
            
            NSArray *array = responseObject[@"data"][@"list"];
            
            if (array.count == 0) {
                
                self.tableView.footerReleaseToRefreshText = @"暂无更多数据";
                self.tableView.footerRefreshingText = @"暂无更多数据";
            }
            else
            {
                
                [_dataArray addObjectsFromArray:array];
                
            }
            
            [self.tableView reloadData];
            [self.tableView footerEndRefreshing];
            
        }
        else
        {
            
            [self.tableView footerEndRefreshing];
            NSString *str = [NSString stringWithFormat:@"%@",responseObject[@"result_msg"]];
            UIAlertView *alter = [[UIAlertView alloc]initWithTitle:@"提示" message:str delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [alter show];
            
            if ([responseObject[@"result_code"] isEqualToString:@"ERR-WHO-0005"]) {
                
                //将所有存储的数据进行清除，并且跳转到登录界面
                [self.dataHandler removeLocalData:@"wTel"];
                LoginViewController *login = [[LoginViewController alloc]initWithNibName:nil bundle:nil];
                [self presentViewController:login animated:YES completion:nil];
            }
            
        }
        
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        [self.tableView footerEndRefreshing];
        [self.view makeToast:@"请检查网络"];
        
    }];

    
    
    
    
    
    
}

- (void)getDate {

   [self getGoodsListByServicePage:currentPage size:sizeCount];
    
    
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    
    SourceDetailController *detailsVC = [[SourceDetailController alloc] initWithNibName:nil bundle:nil];
    detailsVC.messageDic = self.dataArray[indexPath.row];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"pushToSubControllerClick" object:nil userInfo:@{@"controller":detailsVC}];
    
  
}
@end
